package com.jgdt.jgdtkasannong_university_gene_backend.service.content.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jgdt.jgdtkasannong_university_gene_backend.common.Sysconstant;
import com.jgdt.jgdtkasannong_university_gene_backend.config.enums.FilePatternsEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.config.enums.SysValueSetEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.content.Media;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.content.MediaMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.MediaService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.sys.SysValueSetService;
import com.jgdt.jgdtkasannong_university_gene_backend.utils.excel.ImageUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.env.Environment;

/**
 * <p>
 * 影像存储表 服务实现类
 * </p>
 *
 * @author chenzg
 * @since 2025-04-24
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper,Media> implements MediaService {

    @Autowired
    private MediaMapper mediaMapper;
    @Resource
    private Environment environment;

    @Autowired
    private SysValueSetService sysValueSetService;


    @Override
    public List<Media> queryByContentId(List<Integer> contentGeneralList, Integer type, Integer bizType) {
        LambdaQueryWrapper<Media> queryWrapper=new LambdaQueryWrapper<>();
        if(CollectionUtil.isNotEmpty(contentGeneralList)){
            queryWrapper.in(Media::getContentId,contentGeneralList);
        }
        if(type!=null){
            queryWrapper.eq(Media::getType,type);
        }
        if(bizType!=null){
            queryWrapper.eq(Media::getBizType,bizType);
        }
        return mediaMapper.selectList(queryWrapper);
    }

    @Override
    public List<Media> queryByBaseId(List<Integer> baseIds, Integer type, Integer bizType) {
        LambdaQueryWrapper<Media> queryWrapper = new LambdaQueryWrapper<>();
        if (CollectionUtil.isNotEmpty(baseIds)) {
            queryWrapper.in(Media::getBaseId, baseIds);
        }
        if (type != null) {
            queryWrapper.eq(Media::getType, type);
        }
        if (bizType != null) {
            queryWrapper.eq(Media::getBizType, bizType);
        }
        return mediaMapper.selectList(queryWrapper);
    }

    @Override
    public void saveUpdateById(List<Media> medias) {
        this.saveOrUpdateBatch(medias);
    }

    @Override
    public void deleteBatchBaseIds(List<Integer> delMediaIds) {
        LambdaQueryWrapper<Media> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Media::getBaseId,delMediaIds);
        List<Media> mediaIds=this.list(queryWrapper);
        if(CollectionUtil.isEmpty(mediaIds)){
            return;
        }
        List<Integer> ids=mediaIds.stream().map(Media::getId).collect(Collectors.toList());
        baseMapper.deleteBatchIds(ids);
    }

    @Override
    public String getImgUrl(String img) {
        if (StringUtils.isEmpty(img)) {
            log.warn("warn getImgUrl img为空!");
            return null;
        }
        try {
            String ipPort=getImgUrlHttp();
            String slipIndex=null;
//            String code= FilePatternsEnums.getEnumsByIsEnable().getCode();
            String code= this.getFilePatternsCode();
            if(FilePatternsEnums.WIDOS.getCode().equals(code)){
                slipIndex= FilePatternsEnums.getEnumsByCode(FilePatternsEnums.WIDOS.getCode()).getSlipIndex();
            }else if(FilePatternsEnums.LINX.getCode().equals(code)){
                slipIndex=  FilePatternsEnums.getEnumsByCode(FilePatternsEnums.LINX.getCode()).getSlipIndex();
            }else{
                log.warn("getAfterLastSlash warn:配置文件FilePatternsEnums.java有问题");
            }
            String imgName=ImageUtils.getAfterLastSlash(img,slipIndex,code);
            return Sysconstant.HTTP_INDEX +ipPort+"/"+ SysValueSetEnums.FRONT_VISIT_IMG_PREFIX.getValue()+"/"+imgName;
        }catch (Exception e){
            log.error("getImgUrl err:"+e.getMessage());
        }
        return null;
    }

    @Override
    public String generateDomainName() {
        String domainName = null;
        try {
            String ip = ImageUtils.getLocalIP();
            String port = environment.getProperty("server.port", "8080");  // 获取端口，默认8080
            domainName = ip + ":" + port;
        } catch (Exception e) {
            log.error("generateDomainName err:" + e.getMessage());
        }
        return domainName;
    }

    @Override
    public String getImgUrlHttp() {
        // 优先级 值集配置>系统生成>枚举默认配置
        String frontVisitImgDomain = null;
        frontVisitImgDomain = sysValueSetService.queryPriorityValueByCode(SysValueSetEnums.FRONT_VISIT_IMG_DOMAIN.getCode());
        if(StringUtils.isNotEmpty(frontVisitImgDomain)){
            return frontVisitImgDomain;
        }
        frontVisitImgDomain = this.generateDomainName();
        if(StringUtils.isNotEmpty(frontVisitImgDomain)){
            return frontVisitImgDomain;
        }
        return SysValueSetEnums.getEnumsCode(SysValueSetEnums.FRONT_VISIT_IMG_DOMAIN.getCode()).getValue();
    }

    @Override
    public String getFilePatternsCode() {
        //优先级 值集配置>枚举配置
        String code = sysValueSetService.queryPriorityValueByCode(SysValueSetEnums.FILE_PATTERNS_ENUMS.getCode());
        if (StringUtils.isNotEmpty(code)) {
            return code;
        }
        return FilePatternsEnums.getEnumsByIsEnable().getCode();
    }

    @Override
    public void deleteByGeneralIds(List<Integer> generalIds) {
        LambdaQueryWrapper<Media> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Media::getContentId, generalIds);
        List<Media> mediaList = this.list(lambdaQueryWrapper);
        if (CollectionUtil.isNotEmpty(mediaList)) {
            mediaMapper.deleteBatchIds(mediaList.stream().map(Media::getId).collect(Collectors.toList()));
        }
    }
}
